#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<fcntl.h>
#include<dirent.h>




char  buf[128];
//char  ds18b20_path[64]="/sys/bus/w1/devices/";
DIR  *dirp=NULL;
struct dirent *direntp=NULL;
char chip[32];
char *ptr=NULL;
float temp;


int get_temperature()
{
  int fd=-1;
  int found =0;

char  ds18b20_path[64]="/sys/bus/w1/devices/";
  dirp=opendir(ds18b20_path);
  if(!dirp)
  {
      printf("open folder %s fail:%s",ds18b20_path,strerror(errno));
  }

  while(NULL!=(direntp=readdir(dirp)))
  {
      if(strstr(direntp->d_name,"28-"))
      {
       strncpy(chip,direntp->d_name,sizeof(chip));
       found=1;
      }
      printf("filename:%s\n",direntp->d_name);
  }
  closedir(dirp);
  

  if(!found)
  {
      printf("no found ds18b20\n");
      return -1;
  }


  strncat(ds18b20_path,chip,sizeof(ds18b20_path)-strlen(ds18b20_path));
  strncat(ds18b20_path,"/w1_slave",sizeof(ds18b20_path)-strlen(ds18b20_path));
  printf("ds18b20_path:%s\n",ds18b20_path);

  fd=open(ds18b20_path,O_RDONLY);
  if(fd<0)
  {
      printf("open file fail %s\n",strerror(errno));
      return -1;
  }


  memset(buf,0,sizeof(buf));
  if(read(fd,buf,sizeof(buf))<0)
  {
      printf("read data from fd=%s\n",fd,strerror(errno));
  }
  printf("buf:%s\n",buf);
  ptr=strstr(buf,"t=");
  if(!ptr)
  {
      printf("no t=");
      close(fd);
  }
  ptr+=2;
  temp=0;
  temp =atof(ptr)/1000;
  printf("temp_1:%f\n",temp);
}



int main(char argc,char* argv[])
{
  int rv_ds18b20;
  rv_ds18b20=get_temperature();
  if(rv_ds18b20<0)
  {
       printf("get temp fail,return value:%d",rv_ds18b20);
  }
  printf("temp_2:%f\n",temp);

  rv_ds18b20=get_temperature();


}
